/*
 * $Id$
 */
package py.windmill.dict;

import java.io.BufferedInputStream;

import java.sql.Blob;
import java.sql.ResultSet;

import java.util.zip.GZIPInputStream;

import javax.sql.DataSource;

import py.windmill.util.DataSources;
import py.windmill.util.Query;
import py.windmill.util.RowMapper;

/**
 * Reads entry definition from the database.
 *
 * @author myang
 */
public class EntryDbReader implements EntryReader {

    private final static DataSource DS = DataSources.getDataSource();

    @Override
    public String read(final String entry) {
        final Query qr = new Query(DS, "select * from dict_definitions where entry = ?");
        return qr.first(new RowMapper<String>() {
            @Override
            public String mapRow(final ResultSet rs) throws Exception {
                final Blob b = rs.getBlob("definition");
                final BufferedInputStream bis =
                  new BufferedInputStream(new GZIPInputStream(b.getBinaryStream()));
                final byte[] bb = new byte[rs.getInt("size")];
                try {
                    bis.read(bb);
                    return new String(bb, "UTF-8");
                } finally {
                    if (null != bis) {
                        bis.close();
                    }
                }
            }
        }, entry);
    }
}
